package net.esj.basic.utils.hibe;

import net.esj.basic.dao.querybuilder.QueryBuilder;
import net.esj.basic.utils.view.JSONUtil;

import org.hibernate.collection.internal.PersistentBag;
import org.hibernate.collection.internal.PersistentSet;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.LazyInitializer;
import org.json.JSONException;

public class Hi4JSONUtil extends JSONUtil  {
	
	private static Hi4JSONUtil instance = null;

	static public String toJSONString(Object obj) throws JSONException {
        return toJSONString(obj,null, false);
    }
   
	static public String toJSONString(Object obj,Class structClass, boolean useClassConvert) throws JSONException {
        if(instance == null)
            instance = new Hi4JSONUtil();
        return instance.getJSONObject(obj,structClass, useClassConvert).toString();
    }

    @Override
    protected Object proxyCheck(Object bean) {
//        System.out.println("Class is " + bean.getClass().getName());
        if(bean instanceof HibernateProxy) {
            LazyInitializer lazyInitializer = ((HibernateProxy)bean).getHibernateLazyInitializer();
            //if(lazyInitializer.isUninitialized()) {//不管有没有初始化都要返回ID，否则会死循环
//                System.out.println(">>>>>lazyInitializer.getIdentifier()="+ lazyInitializer.getIdentifier());
                return lazyInitializer.getIdentifier();
            //}
        }
        if(bean instanceof PersistentSet) {
            return new String[] {}; //忽略hibernate one-to-many
        }
        if(bean instanceof PersistentBag){
        	return new String[]{};
        }
        if(bean instanceof QueryBuilder){
        	return "";
        }
        return super.proxyCheck(bean);
    }
}
